package com.cll.pmis.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cll.pmis.common.Constants;
import com.cll.pmis.common.exception.PmisException;
import com.cll.pmis.common.security.BCryptPasswordUtil;
import com.cll.pmis.common.security.SysUser;
import com.cll.pmis.entity.Menu;
import com.cll.pmis.entity.User;
import com.cll.pmis.mapper.UserMapper;
import com.cll.pmis.service.IMenuService;
import com.cll.pmis.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    private IMenuService menuService;

    protected UserServiceImpl(IMenuService menuService) {
        this.menuService = menuService;
    }

    @Override
    public SysUser login(String username, String password) {
        User userPo = new User();
        userPo.setUsername(username);
        User user = this.baseMapper.selectOne(userPo);
        if (user == null) {
            throw new PmisException("用户不存在");
        }

        boolean matches = BCryptPasswordUtil.matches(password, user.getPassword());
        if (!matches) {
            throw new PmisException("密码错误");
        }
        Integer uid = user.getId();
        String role = this.baseMapper.queryRole(uid);
        HashSet<String> permSet = new HashSet<>();
        List<String> perms;
        //超级管理员加载所有权限
        if (uid == Constants.SUPER_ADMIN) {
            List<Menu> menus = menuService.selectList(null);
            perms = new ArrayList<>(menus.size() * 4 / 3);
            for (Menu menu : menus) {
                perms.add(menu.getPerms());
            }
        } else {
            perms = this.baseMapper.queryPerms(uid);
        }

        for (String perm : perms) {
            if (StringUtils.isEmpty(perm)){
                continue;
            }
            if (perm.contains(";")) {
                String[] split = StringUtils.split(perm, ";");
                permSet.addAll(Arrays.asList(split));
            } else {
                permSet.add(perm);
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(uid);
        sysUser.setUsername(user.getUsername());
        sysUser.setRole(role);
        sysUser.setPerms(permSet);
        return sysUser;
    }
}
